package com.cljz.peipei.base;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.cljz.peipei.ui.activity.LoginActivity;
import com.cljz.peipei.utils.T;
import com.cljz.peipei.widget.LoadingDialog;
import com.clzj.peipei.dao.DaoSession;
import com.tbruyelle.rxpermissions.Permission;
import com.umeng.analytics.MobclickAgent;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.mvp.IPresent;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/3/31.
 */

public abstract class BaseActivity<P extends IPresent> extends XActivity<P> {
    private static final int DISMISS_DIALOG = 233;
    public static final int EXIT = 666;
    private LoadingDialog loadingDialog;
    private ComponentName component;
    final Handler dialogHandler = new DialogHandler(this);
    public DaoSession daoSession;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        daoSession = ((App) App.instance).getDaoSession();
        App.setInstanceRef(this);
        com.cljz.peipei.utils.ActivityManager.getInstance().addActivity(this);
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo cinfo = runningTasks.get(0);
        component = cinfo.topActivity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        App.setInstanceRef(this);
        MobclickAgent.onPageStart(component.getClassName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissLoadingDialog();
        MobclickAgent.onPageEnd(component.getClassName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dialogHandler.removeCallbacksAndMessages(null);
        com.cljz.peipei.utils.ActivityManager.getInstance().removeActivity(this);
        //每次在activity销毁的时候调用该函数来检测应用是否被销毁
        App.checkApplicationDestroy();
    }

    public void showLoadingDialog() {
        loadingDialog = new LoadingDialog(App.getInstance());
        loadingDialog.show();
        backgroundAlpha(0.5f);
        dialogHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 20000);
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            dialogHandler.removeCallbacksAndMessages(null);
            loadingDialog.dismiss();
            loadingDialog = null;
            backgroundAlpha(1.0f);
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        //Log.e("backgroundAlpha", bgAlpha + "");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 在ActionBarActivity中，如果设置窗口主题为全屏无标题栏，则需要禁止menu键，否则程序报错崩溃
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private static class DialogHandler extends Handler {
        private final WeakReference<BaseActivity> mActivity;

        DialogHandler(BaseActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseActivity activity = mActivity.get();
            switch (msg.what) {
                case DISMISS_DIALOG:
                    activity.dismissLoadingDialog();
                    T.getInstance().showShort("网络超时");
                    break;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissLoadingDialog();
    }

    protected void showSnackBar(View view, String msg) {
        Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).show();
    }

    public void loginOvertime(int loginFail) {
        if (EXIT != loginFail){
            T.getInstance().showShort("已在其他设备登录");
        }
        daoSession.getUserInfoDao().deleteByKey(SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""));
        SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, "");
        Router.newIntent((Activity) App.getInstance()).to(LoginActivity.class).launch();
        com.cljz.peipei.utils.ActivityManager.getInstance().finishAfterActivity(LoginActivity.class);
    }

    protected void initPermission() {
        getRxPermissions().requestEach(Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.READ_PHONE_STATE
                , Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        if (permission.name.equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                            if (!permission.granted) {
                                T.getInstance().showShort("请开启定位权限");

                            }
                        } else if (permission.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            if (!permission.granted) {
                                T.getInstance().showShort("请开启存储权限");
                            }
                        } else if (permission.name.equals(Manifest.permission.CAMERA)) {
                            if (!permission.granted) {
                                T.getInstance().showShort("请开启相机权限");
                            }
                        }
                    }
                });
    }

}
